package com.itjin.controller;

import com.itjin.model.domain.dto.EmailDTO;
import com.itjin.model.domain.entity.Post;
import com.itjin.model.domain.entity.PostReport;
import com.itjin.model.domain.vo.HotUpdateConfigVO;
import com.itjin.model.result.Result;
import com.itjin.service.ConfigService;
import com.itjin.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itjin.mapper.PostMapper;
import com.itjin.mapper.PostReportMapper;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/")
@Tag(name = "健康检查")
@Slf4j
public class MainController {
  @Autowired
  private JavaMailSender mailSender;

  @SuppressWarnings("rawtypes")
  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private ConfigService configService;

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private PostMapper postMapper;

  @Autowired
  private PostReportMapper postReportMapper;

  /**
   * 健康检查
   */
  @Operation(summary = "健康检查")
  @GetMapping("/health")
  public Result<String> health() {
    return Result.success("ok");
  }

  /**
   * 版本检查热更新
   */
  @Operation(summary = "版本检查热更新")
  @GetMapping("/version")
  public Result<List<HotUpdateConfigVO>> version(
      @RequestParam String currentVersion,
      @RequestParam String platform) {
    try {
      if (currentVersion == null || currentVersion.isEmpty()) {
        return Result.failure(400, "当前版本不能为空");
      }
      if (platform == null || platform.isEmpty()) {
        return Result.failure(400, "平台不能为空");
      }

      List<HotUpdateConfigVO> configs = configService.getLatestConfigs(currentVersion, platform);
      return Result.success(configs);
    } catch (IllegalArgumentException e) {
      log.error("版本检查参数错误: {}", e.getMessage());
      return Result.failure(400, e.getMessage());
    } catch (Exception e) {
      log.error("版本检查失败", e);
      return Result.failure(500, "版本检查失败: " + e.getMessage());
    }
  }

  /**
   * 验证码发送
   */
  @SuppressWarnings("unchecked")
  @Operation(summary = "验证码发送")
  @PostMapping("/captcha")
  public Result<String> captcha(@RequestBody EmailDTO email) {
    // 生成验证码
    String verificationCode = generateVerificationCode();
    // 创建邮件对象
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("3338170081@qq.com"); // 发件人邮箱
    message.setTo(email.getEmail());
    message.setSubject("树岛 - 验证码");
    message.setText("您的验证码是：" + verificationCode + "\n验证码有效期为5分钟，请勿泄露给他人。");
    try {
      // 发送邮件
      mailSender.send(message);

      // 将验证码存入Redis，设置5分钟过期
      String redisKey = "email:code:" + email.getEmail();
      redisTemplate.opsForValue().set(redisKey, verificationCode, 5, TimeUnit.MINUTES);
      log.info("验证码发送成功！验证码：" + verificationCode);
      return Result.success("验证码发送成功！");
    } catch (Exception e) {
      log.error("验证码发送失败：" + e.getMessage());
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * 生成6位随机验证码
   */
  private String generateVerificationCode() {
    Random random = new Random();
    StringBuilder code = new StringBuilder();
    for (int i = 0; i < 6; i++) {
      code.append(random.nextInt(10));
    }
    return code.toString();
  }

  /**
   * 获取数据看板
   */
  @Operation(summary = "获取数据看板")
  @GetMapping("/dashboard")
  public Result<Map<String, Object>> getDashboard() {
    try {
      Map<String, Object> dashboardData = new HashMap<>();

      // 1. 获取用户总数
      Long totalUsers = userMapper.selectCount(null);
      dashboardData.put("totalUsers", totalUsers);

      // 2. 统计活跃量
      Date now = new Date();
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(now);

      // 设置为今天开始时间
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.MILLISECOND, 0);
      Date todayStart = calendar.getTime();

      // 设置为本周开始时间（周一）
      calendar.setTime(now);
      calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.MILLISECOND, 0);
      Date weekStart = calendar.getTime();

      // 设置为本月开始时间
      calendar.setTime(now);
      calendar.set(Calendar.DAY_OF_MONTH, 1);
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.MILLISECOND, 0);
      Date monthStart = calendar.getTime();

      // 设置为本年开始时间
      calendar.setTime(now);
      calendar.set(Calendar.MONTH, Calendar.JANUARY);
      calendar.set(Calendar.DAY_OF_MONTH, 1);
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.MILLISECOND, 0);
      Date yearStart = calendar.getTime();

      // 查询活跃用户数（根据登录记录或操作记录）
      Integer dailyActiveUsers = userMapper.countActiveUsersByTime(todayStart, now);
      Integer weeklyActiveUsers = userMapper.countActiveUsersByTime(weekStart, now);
      Integer monthlyActiveUsers = userMapper.countActiveUsersByTime(monthStart, now);
      Integer yearlyActiveUsers = userMapper.countActiveUsersByTime(yearStart, now);

      Map<String, Integer> activeUsers = new HashMap<>();
      activeUsers.put("daily", dailyActiveUsers);
      activeUsers.put("weekly", weeklyActiveUsers);
      activeUsers.put("monthly", monthlyActiveUsers);
      activeUsers.put("yearly", yearlyActiveUsers);
      dashboardData.put("activeUsers", activeUsers);

      // 3. 获取已发布帖子总数
      Long publishedPosts = postMapper.selectCount(
          new QueryWrapper<Post>().eq("postStatus", 3));
      dashboardData.put("publishedPosts", publishedPosts);

      // 4. 获取待审核总数
      Long pendingPosts = postMapper.selectCount(
          new QueryWrapper<Post>().eq("postStatus", 1));
      dashboardData.put("pendingPosts", pendingPosts);

      // 5. 获取已删除总数
      Long deletedPosts = postMapper.selectCount(
          new QueryWrapper<Post>().eq("postStatus", 2));
      dashboardData.put("deletedPosts", deletedPosts);

      // 6. 获取不同时间段的帖子数量
      Long todayPosts = postMapper.selectCount(
          new QueryWrapper<Post>()
              .eq("postStatus", 3)
              .ge("createTime", todayStart));

      Long weekPosts = postMapper.selectCount(
          new QueryWrapper<Post>()
              .eq("postStatus", 3)
              .ge("createTime", weekStart));

      Long monthPosts = postMapper.selectCount(
          new QueryWrapper<Post>()
              .eq("postStatus", 3)
              .ge("createTime", monthStart));

      Long yearPosts = postMapper.selectCount(
          new QueryWrapper<Post>()
              .eq("postStatus", 3)
              .ge("createTime", yearStart));

      Map<String, Long> postsTimeline = new HashMap<>();
      postsTimeline.put("today", todayPosts);
      postsTimeline.put("week", weekPosts);
      postsTimeline.put("month", monthPosts);
      postsTimeline.put("year", yearPosts);
      dashboardData.put("postsTimeline", postsTimeline);

      // 7. 获取不同时间段的举报量
      Long todayReports = postReportMapper.selectCount(
          new QueryWrapper<PostReport>()
              .ge("createTime", todayStart));

      Long weekReports = postReportMapper.selectCount(
          new QueryWrapper<PostReport>()
              .ge("createTime", weekStart));

      Long monthReports = postReportMapper.selectCount(
          new QueryWrapper<PostReport>()
              .ge("createTime", monthStart));

      Long yearReports = postReportMapper.selectCount(
          new QueryWrapper<PostReport>()
              .ge("createTime", yearStart));

      Map<String, Long> reportsTimeline = new HashMap<>();
      reportsTimeline.put("today", todayReports);
      reportsTimeline.put("week", weekReports);
      reportsTimeline.put("month", monthReports);
      reportsTimeline.put("year", yearReports);
      dashboardData.put("reportsTimeline", reportsTimeline);

      return Result.success(dashboardData);
    } catch (Exception e) {
      log.error("获取数据看板失败", e);
      return Result.failure(500, "获取数据看板失败: " + e.getMessage());
    }
  }
}